package com.rivues.module.design.web.handler.player;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.rivues.core.RivuDataContext;
import com.rivues.module.account.web.handler.LoginController;
import com.rivues.module.platform.web.model.AnalyzerReport;
import com.rivues.module.platform.web.model.AnalyzerReportModel;
import com.rivues.module.platform.web.model.ReportFilter;
import com.rivues.module.report.web.handler.ReportHandler;
import com.rivues.module.report.web.model.PublishedReport;
import com.rivues.util.iface.report.ReportFactory;
import com.rivues.util.serialize.JSON;

@Controller
@RequestMapping("/{orgi}/analyzerReport/dataDesign/view")
public class ReportDesignController extends ReportHandler {
	/**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{reportcode}" , name="querydesign" , type="design",subtype="query")
    public ModelAndView querydesign(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportcode) throws Exception{
    	ModelAndView view = null;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByName(super.getUser(request), orgi, reportcode ) ;
    	
    	if(report.getHtml()!=null && report.getHtml().equals("1")){
    		//允许匿名用户从移动端访问报表
    	}else if(super.getUser(request).getUsername().equals(RivuDataContext.GUEST_USER)){
    		return new LoginController().login(request, orgi) ;
    	}
    	if(report != null){
    		AnalyzerReport analyzerReport = report.getReport();
    		if("true".equals(report.getExtparam())){
    			view = request(super.createManageResponse("/pages/design/player/index") , orgi) ;
    		}else{
    			view = request(super.createManageResponse("/pages/user/report/view/reportview") , orgi) ;
    		}
    		
    		AnalyzerReportModel reportModel = null ;
    		if(analyzerReport.getModel().size()>0){
    			for(AnalyzerReportModel model : analyzerReport.getModel()){
    				if(reportModel==null){
    					reportModel = model ;
    					break;
    				}
    			}
    		}
    		
    		super.processRequestParam(analyzerReport, request , true) ;
    		boolean flag = viewsign(request, orgi, analyzerReport);
    		if(flag){
    			if(reportModel != null){
    				/**
    				 * 以下代码用于
    				 */
    				for(ReportFilter reportFilter : analyzerReport.getFilters()){
    					if(RivuDataContext.ReportCompareEnum.RANGE.toString().equals(reportFilter.getValuefiltertype())){
    						if(RivuDataContext.FilterConValueEnum.AUTO.toString().equals(reportFilter.getConvalue())){
    							String start = request.getParameter(reportFilter.getCode()+"_start")!=null ? request.getParameter(reportFilter.getCode()+"_start") : "" ;
    							String end = request.getParameter(reportFilter.getCode()+"_end")!=null ? request.getParameter(reportFilter.getCode()+"_end") : "" ;
    							if((start.length() - start.replaceAll(".", "").length()) != (end.length() - end.replaceAll(".", "").length())){
    								continue ;
    							}
    						}
    						reportFilter.setRequeststartvalue(request.getParameter(reportFilter.getCode()+"_start")) ;
    						reportFilter.setRequestendvalue(request.getParameter(reportFilter.getCode()+"_end")) ;
    					}else{
    						if(request.getParameter(reportFilter.getCode())!=null){
    							reportFilter.setRequestvalue(request.getParameter(reportFilter.getCode())) ;
    						}
    					}
    					if(!reportFilter.getId().equals(reportFilter.getCode())){
    						reportFilter.setRequest(true) ;
    					}
    				}
    			}
    			report.setReport(analyzerReport);
    			/**
    			 * 创建视图
    			 */
    			/**
    			 * 更新缓存
    			 */
    			updateCacheReport(request , report , analyzerReport , orgi , true) ;
    			/**
    			 * 将当期编辑的报表放入分布式缓存中，报表编辑器退出的时候需要清理该报表，同样的，在用户退出的时候，也需要清理缓存中的垃圾
    			 */
    			return createModelAndView(view , report , request , reportModel , false,true);
    		}else{
    			view = request(super.createManageResponse("/pages/design/player/errorpage") , orgi) ;
    			view.addObject("report", analyzerReport);
    			/**
    			 * 将当期编辑的报表放入分布式缓存中，报表编辑器退出的时候需要清理该报表，同样的，在用户退出的时候，也需要清理缓存中的垃圾
    			 */
    			return createModelAndView(view , report , request , reportModel , false ,report.getObjectcount()==0?false:true);
    		}
    	}else{
    		view = request(super.createManageResponse("/pages/design/player/errorpage") , orgi) ;
			view.addObject("report", report);
    		return view ;
    	}
    	
    	
    }

	public static String getMD5(byte[] source) {
		String s = null;
		char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
				'e', 'f' };
		try {
			java.security.MessageDigest md = java.security.MessageDigest
					.getInstance("MD5");
			md.update(source);
			byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数，
										// 用字节表示就是 16 个字节
			char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话，使用两个字符，
											// 所以表示成 16 进制需要 32 个字符
			int k = 0; // 表示转换结果中对应的字符位置
			for (int i = 0; i < 16; i++) { // 从第一个字节开始，对 MD5 的每一个字节
											// 转换成 16 进制字符的转换
				byte byte0 = tmp[i]; // 取第 i 个字节
				str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
															// >>>
															// 为逻辑右移，将符号位一起右移
				str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
			}
			s = new String(str); // 换后的结果转换为字符串

		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}
	/**
	 * 与其它业务系统集成
	 * @param request
	 * @param modelid
	 * @param orgi
	 * @param report
	 * @return
	 * @throws Exception
	 */
	public boolean viewsign(HttpServletRequest request,String orgi , AnalyzerReport report) throws  Exception{
		boolean returnFlag = false;
		String queryString = request.getQueryString();
		if(report.getModel()!=null){
			if(queryString != null){
				//获取最后一个&的位置
				int end = queryString.toString().lastIndexOf("&");
				//获取参数值的串
				String strOld = URLDecoder.decode(queryString.toString().substring(0,end), "utf-8");
				String strNew = strOld.replaceAll("&", ",");
				String v_sign_my = getMD5(strNew.getBytes("utf-8"));
				String v_sign = request.getParameter("v_sign");
				if(v_sign!=null && v_sign.length()>0){
					if(v_sign.equals(v_sign_my)){
						returnFlag = true;
					}
				}
			}else{
				returnFlag = true;
			}
		}
		return returnFlag ;
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(URLEncoder.encode("v_channel=个险&v_secondOrgan=北京&v_thirdOrgan=all&v_start=2014/07/09&v_end=2014/07/23&v_sign=10cad5b4e80192a10aceed320a8d6352", "utf-8"));
		System.out.println(URLDecoder.decode("http://localhost:8080/rivues/analyzerReport/dataDesign/view/XQYKH2014.html?v_channel=%E4%B8%AA%E9%99%A9&v_secondOrgan=%E5%8C%97%E4%BA%AC&v_thirdOrgan=all&v_start=2014-07-09&v_end=2014-07-23&v_sign=10cad5b4e80192a10aceed320a8d6352", "utf-8"));
	}
}